package com.zsk.controller;

import java.util.concurrent.TimeUnit;

import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import io.swagger.annotations.ApiOperation;

@RestController
@RequestMapping("/api-redis")
public class controller {

    public static int PRODUCT_NUM = 1000;
    public static int SELL_NUM = 0;

    @Autowired
    private RedissonClient redisson;

    @ApiOperation(value = "购买商品加分布式锁")
    @GetMapping("/buy/{num}")
    public String sell(@PathVariable int num) {
        RLock lock = redisson.getLock("test_key");
        try {
            boolean ok = lock.tryLock(50, 55, TimeUnit.MILLISECONDS);
            if (ok) {
                if (SELL_NUM >= PRODUCT_NUM || SELL_NUM + num > PRODUCT_NUM) {
                    return "沒有库存啦";
                }
                SELL_NUM += num;
                lock.unlock();
                return "购买成功";
            }
            return "系统繁忙，请稍后";

        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {

        }
        return "系统出错啦";
    }

    @ApiOperation(value = "购买商品不加分布式锁")
    @GetMapping("/buy/nonelock/{num}")
    public String sellNoneLock(@PathVariable int num) {
        try {
            Thread.sleep(5);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        if (SELL_NUM >= PRODUCT_NUM || SELL_NUM + num > PRODUCT_NUM) {
            return "沒有库存啦";
        }
        SELL_NUM += num;
        return "购买成功";
    }

    @ApiOperation(value = "获取总库存")
    @GetMapping("/total")
    public int total() {
        return PRODUCT_NUM;
    }

    @ApiOperation(value = "恢复库存")
    @GetMapping("/restore/{num}")
    public int restor(@PathVariable int num) {
        PRODUCT_NUM = num;
        SELL_NUM = 0;
        System.out.println("restore:" + PRODUCT_NUM);
        return PRODUCT_NUM;
    }

}
